using System;
using System.Management.Automation;
using System.Net;
using System.Net.NetworkInformation;

namespace Pscx.Commands.Net
{
    public class PingHostInfo
    {
        readonly IPHostEntry host;
        readonly PingReply reply;
        readonly Exception error;
        readonly int bufferSize;

        public PingHostInfo(IPHostEntry host, PingReply reply, Exception error, int bufferSize)
        {
            this.host = host;
            this.reply = reply;
            this.bufferSize = bufferSize;
            this.error = error;
        }

        public IPHostEntry Host { get { return host; } }
        public PingReply Reply { get { return reply; } }
        public int BufferSize {
            get 
            {
                if(reply.Status == IPStatus.Success)
                    return reply.Buffer.Length;

                return bufferSize;
            } 
        }
        
        public override string ToString()
        {
            if (Reply.Status == IPStatus.Success)
            {
                int ttl = Reply.Options != null ? Reply.Options.Ttl : 128;

                return string.Format("    Reply from {0} bytes={1} time={2}ms TTL={3}",
                    Reply.Address,
                    Reply.Buffer.Length,
                    Reply.RoundtripTime,
                    ttl);
            }
            else
            {
                return string.Format("    {0}", Reply.Status);
            }
        }

        internal void WriteToPipeline(Cmdlet cmd)
        {
            if (cmd.Stopping)
                return;

            if (error != null)
            {
                cmd.WriteError(new ErrorRecord(
                    error,
                    "PingFailed",
                    ErrorCategory.NotSpecified,
                    this));
            }
            else
            {
                cmd.WriteObject(this);
            }
        }
    }
}
